package com.snack.common.log4j;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.FileAppender;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;

/** 
 * %yyyy:4位的年<br>
 * %yy:2位的年<br>
 * %mm:2位的月<br>
 * %dd:2位的日<br>
 * %hh:2位的小时<br>  
 *  详细请关注: readMe.txt 
 * @kleen
 * @version 1.0.0
 */
public class DatedFileAppender extends FileAppender {
 
	private long nextCheck = 0;
 
	private String originFilename = null;

	private String getDatedFilename() {
		String str = originFilename;
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		String time14 = format.format(new Date());
		str = str.replaceAll("%yyyy", time14.substring(0, 4));
		str = str.replaceAll("%yy", time14.substring(0, 4));
		str = str.replaceAll("%mm", time14.substring(4, 6));
		str = str.replaceAll("%dd", time14.substring(6, 8));
		str = str.replaceAll("%hh", time14.substring(8, 10));
		str = str.replaceAll("%nn", time14.substring(10, 12));
		str = str.replaceAll("%ss", time14.substring(12, 14));
		return str;

	}

	@Override
	public void setFile(String file) {
		originFilename = file;
		super.setFile(getDatedFilename());
	}

	@Override
	protected synchronized void subAppend(LoggingEvent event) {
		long n = System.currentTimeMillis();
		if (n >= nextCheck) {
			nextCheck = n + 1000 * 2;
			try {
				switchFilename();
			}
			catch (IOException ioe) {
				LogLog.error("switchFilename() failed.", ioe);
				ioe.printStackTrace();
			}
		}
		super.subAppend(event);
	}
 
	synchronized void switchFilename() throws IOException {
		String datedFilename = getDatedFilename();
		if (!datedFilename.equals(fileName)) {
			try {
				File dir = new File(datedFilename).getParentFile();
				if (!dir.exists()) {
					dir.mkdirs();
				}
				if (!dir.exists()) {
					return;
				}
				setFile(datedFilename, getAppend(), getBufferedIO(), getBufferSize());
			}
			catch (IOException ex) {
				errorHandler.error("setFile(" + datedFilename + ", false) call failed.");
				ex.printStackTrace();
			}
			this.activateOptions();
			fileName = datedFilename;
		}
	}
}
